import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { PostService } from 'src/app/service/post.service';
import { ConfirmationService, MessageService } from 'primeng/api';
import { ApiMenuService } from 'src/app/service/menu.service';

@Component({
    selector: 'app-accept-manage',
    templateUrl: './accept-manage.component.html',
    styleUrls: ['./accept-manage.component.scss'],
    providers: [ConfirmationService, MessageService],
})
export class AcceptManageComponent implements OnInit {
    id: any;
    tableData: any;
    currentData:any;
    currentItem: any;
    hasChange = false;
    constructor(
        private location: Location,
        private route: ActivatedRoute,
        private postService: PostService,
        private confirmationService: ConfirmationService,
        private messageService: MessageService,
        private menuService: ApiMenuService
    ) {
        route.queryParams.subscribe((queryParams) => {
            this.id = queryParams.id;
            console.log(this.id);
        });
    }

    ngOnInit(): void {
        this.search();
        console.log(this.tableData)
    }
    goBack() {
        this.location.back();
    }
    async search() {
        const r = await this.menuService.fetchApiListById({ id: this.id });
        const genChildList = (list) => {
            const res = [];
            list.forEach((item) => {
                if (!item.pid) {
                    res.push(item);
                }
            });
            list.forEach((item) => {
                if (item.pid) {
                    const it = res.find((it) => it.id === item.pid);
                    if (it) {
                        it.children = (it.children || []).concat(item);
                    }
                }
            });
            console.log('res', res);
            return res;
        };
        const genChildListUpdate = (list) => {
            const res = [];
            list.forEach((item) => {
                if (!item.pid) {
                    let temp = { data: null, children: [], expanded: true };
                    temp.data = item;
                    res.push(temp);
                }
            });
            list.forEach((item) => {
                if (item.pid) {
                    const it = res.find(
                        (it) => it.data.id === item.pid
                    );
                    if (it) {
                        let temp = { data: null };
                        temp.data = item;
                        it.children = (it.children || []).concat(temp);
                    }
                }
            });
            return res;
        };

        this.tableData = genChildListUpdate(r || []);
        const it = await this.postService.fetchPostById({ id: this.id });
        this.currentItem = it || {};
        //console.log(this.currentItem)
    }
    selectAllByObj(o) {
      const r = this.tableData
      for (let i = 0; i < r.length; i++) {
        const it = r[i]
        it.data.roleId = o
        if (it.children) {
          for (let j = 0; j < it.children.length; j++) {
            const c = it.children[j]
            c.data.roleId = o
          }
        }
      }
      this.hasChange = true
    }
    selectRow(item) {
      const r = this.tableData
      let current
      for (let i = 0; i < r.length; i++) {
        const it = r[i]
        if (it.data.id === item.id) {
          current = it
          break
        }
        if (it.children) {
          for (let j = 0; j < it.children.length; j++) {
            const c = it.children[j]
            if (c.data.id === item.id) {
              current = c
              break
            }
          }
        }
        if (current) {
          break
        }
      }
      if (current) {
        current.data.roleId = this.id
        this.hasChange = true
      }
    }
    unSelectRow(item) {
      const r = this.tableData
      let current
      for (let i = 0; i < r.length; i++) {
        const it = r[i]
        if (it.data.id === item.id) {
          current = it
          break
        }
        if (it.children) {
          for (let j = 0; j < it.children.length; j++) {
            const c = it.children[j]
            if (c.data.id === item.id) {
              current = c
              break
            }
          }
        }
        if (current) {
          break
        }
      }
      if (current) {
        current.data.roleId = null
        this.hasChange = true
      }
    }
    selectAll() {
      this.selectAllByObj(this.id)
    }
    selectNone() {
      this.selectAllByObj(null)
    }
    reset = async () => {
      await this.search()
      this.hasChange = false
    }
    async save() {
      const genSaveList = list => {
        const res = []
        list.forEach(item => {
          res.push({
            id: item.data.id + '',
            roleId: item.data.roleId,
          })
          item.children &&
            item.children.forEach(it => {
              res.push({
                id: it.data.id + '',
                roleId: it.data.roleId,
              })
            })
        })
        return res.filter(item => item.roleId)
      }
      const res = await this.menuService.saveApiByList({
        id: this.id,
        list: genSaveList(this.tableData),
      })
      if (res.code === '200') {
        this.messageService.add({
          severity: 'info',
          summary: '确认',
          detail: 'API权限已经修改',
      });
        await this.reset()
      }
    }
}
